import React, { useState } from 'react';
import cn from 'classnames';
import i from '@/index.module.css';
import recursionForm from '@/common/recursionForm';
import s from './style.module.css';
import {
    Table,
    Message,
    Dialog,
    Button,
    Confirm,
    Loading,
    Form,
    Input,
    Datetime,
    Radio,
    Tooltip,
    Textarea,
    Select
} from '@knownsec/react-component';
import { postUrl, getUrl, putUrl, delUrl, testUrl } from '~/API';
// import SelectAnt from '@/components/SelectAnt';
import CopyText from '@/components/copy';
import EmptyData from '@/components/EmptyData';

import moment from 'moment';
export default function list() {
    const layout = {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
    };
    const [refe] = useState(false);
    const [selTable, setSelTable] = useState([]);
    const [upVisible, setUpVisible] = useState('');
    const [tableData, setTableData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [showType, setShowType] = useState({});
    const urlForm = React.useRef();
    const disabledate = (current) => {
        return current < moment();
    };
    const getList = async () => {
        setLoading(true);
        setTableData([]);
        const list = await getUrl();
        setTableData(list.data.data);
        setLoading(false);
    };
    React.useMemo(() => {
        getList();
    }, []);
    const submitInfo = async () => {
        let data = await urlForm.current.validateFields();
        data = Object.entries(data).reduce((prev, cur) => {
            if (Array.isArray(cur[1])) {
                if (cur[0] === 'is_active') {
                    prev[cur[0]] = cur[1][0] === 'true' ? true : false
                } else {
                    prev[cur[0]] = cur[1][0]
                }
            } else {
                prev[cur[0]] = cur[1]
            }
            return prev
        }, {})
        if (!data.authentication) {
            data.auth_type = 'no_auth';
            data.auth_key = '';
            data.auth_value = '';
        }
        let res = null;
        let msg = '';
        let type = 'success';
        if (upVisible === '设置推送URL') {
            res = await postUrl(data).catch(err => {return err});
            if (res.status === 'success') {
                msg = '添加成功';
            } else {
                const err = Object.keys(res.data);
                msg = res.data[err[0]][0];
                type = 'error';
            }
        } else {
            res = await putUrl({ id: selTable[0], data }).catch(err => {return err});
            if (res.status === 'success') {
                msg = '修改成功';
            } else {
                const err = Object.keys(res.data);
                msg = res.data[err[0]][0];
                type = 'error';
            }
        }
        if(type=='success'){
            getList();
            setUpVisible(false);
            urlForm.current.resetFields();
          }
        Message.show({
            pro: true,
            showClose: false,
            className:[s.Message],
            type,
            message: msg,
        });
    };
    const changeUrl = (row) => {
        setSelTable([row.id]);
        setUpVisible('修改');
        const obj = ['url', 'auth_key', 'auth_value', 'method', 'is_active', 'desc'];
        const formObj = { expired_time: moment(row.expired_time) };
        if (row.auth_type === 'no_auth') {
            formObj.authentication = false;
            formObj.auth_type = null;
            setShowType({});
        } else {
            if (row.auth_type === 'api_key') {
                setShowType({ auth: { key: 1 } });
            } else {
                setShowType({ auth: { user: 1 } });
            }
            formObj.authentication = true;
            formObj.auth_type = [row.auth_type];
        }
        obj.forEach((e) => {
            if (e === 'method' || e === 'is_active') {
                formObj[e] = [row[e] + ''];
            } else {
                formObj[e] = row[e];
            }
        });
        urlForm.current.setFieldsValue(formObj);
    };
    const columns = [
        {
            title: 'URL地址',
            dataIndex: 'url',
            render: (value) => {
                return (
                    <Tooltip
                        overlay={
                            <p>
                                URL地址：
                                <CopyText text={value} />
                            </p>
                        }
                        placement="topLeft"
                    >
                        <div className={s.td_omit}>{value}</div>
                    </Tooltip>
                );
            },
        },
        {
            title: '认证类型',
            dataIndex: 'auth_type',
            className: s.td_5,
            render: (val) => {
                return val === 'no_auth' ? '--' : val;
            },
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            className: s.td_12,
            render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),
        },
        {
            title: '过期时间',
            dataIndex: 'expired_time',
            className: s.td_12,
            render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),
        },
        {
            title: '备注',
            dataIndex: 'desc',
            render: (value) => {
                return (
                    <Tooltip
                        overlay={
                            <p style={{ "max-width": ' 50vw', 'word-break': 'break-word' }}>
                                备注：{value}
                            </p>
                        }
                        placement="topLeft"
                    >
                        <div className={s.td_omit}>{value || '--'}</div>
                    </Tooltip>
                );
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            className: s.w_5,
            render: (e, row) => {
                const id = row.id;
                return (
                    <div className={s.btnBox}>
                        <div
                            className={s.operation}
                            onClick={async () => {
                                changeUrl(row);
                            }}
                        >
                            修改
                        </div>
                        <div
                            className={s.operation}
                            onClick={() => {
                                testURLfn(row);
                            }}
                        >
                            测试
                        </div>
                        <div
                            className={s.operation}
                            onClick={() => {
                                delList(id);
                            }}
                        >
                            删除
                        </div>
                    </div>
                );
            },
        },
    ];
    const testURLfn = (row) => {
        Confirm({
            pro: true,
            title: '测试推送URL',
            message: (
                <div className="confirmbox">
                    为确保数据推送正常，您可测试数据是否可成功推送至填写URL地址。
                </div>
            ),
            onconfirm: async () => {
                const res = await testUrl({ url_id: row.url_id }).catch((e) => {
                    return { status: 'fail' };
                });
                if (res.status === 'success') {
                    Message.show({
                        pro: true,
                        className:[s.Message],
                        showClose: false,
                        type: 'success',
                        message: '推送成功',
                    });
                } else {
                    Message.show({
                        pro: true,
                        className:[s.Message],
                        showClose: false,
                        type: 'error',
                        message: '推送失败，请查看配置是否正常',
                    });
                }
            },
            oncancel: () => {},
        });
    };
    const delList = (e) => {
        Confirm({
            pro: true,
            title: '提示',
            message: <div className="confirmbox">删除后，推送URL设置立即失效，您确定要删除？</div>,
            onconfirm: async () => {
                const res = await delUrl({ id: e });
                getList();
                if (res.status === 'success') {
                    Message.show({
                        pro: true,
                        className:[s.Message],
                        showClose: false,
                        type: 'success',
                        message: '删除成功',
                    });
                }
            },
            oncancel: () => {},
        });
    };
    const onValues = (data) => {
        let values = recursionForm(data);
        if ({}.propertyIsEnumerable.call(values, 'authentication')) {
            if (values.authentication) {
                setShowType({ auth: {} });
            } else {
                setShowType({});
                urlForm.current.setFieldsValue({ auth_type: null });
            }
        }
        if ({}.propertyIsEnumerable.call(values, 'auth_type')) {
            if (values.auth_type[0] === 'api_key') {
                setShowType({ auth: { key: 1 } });
            } else {
                setShowType({ auth: { user: 1 } });
            }
            urlForm.current.setFieldsValue({ auth_key: '', auth_value: '' });
        }
        urlForm.current.setFieldsValue(values);
    };
    const initFormData = () => {
        setShowType({});
        urlForm.current.setFieldsValue({ authentication: false, is_active: ['true'] });
    };
    const validatormap = (rule, value, callback) => {
        if (value && value.length > 200) {
            callback('最多输入200字符');
        } else {
            return Promise.resolve();
        }
    };
    React.useEffect(() => {
        initFormData();
    }, []);
    return (
        <div className={s.wordMain}>
            <div className={s.tool}>
                <Button
                    type="primary"
                    pro
                    disabled={tableData.length}
                    onClick={() => {
                        setUpVisible('设置推送URL');
                        initFormData();
                    }}
                >
                    设置URL
                </Button>
            </div>
            {/* <Loading show={loading} /> */}
            <Table
                refre={refe}
                tableLoading={loading}
                loadingLabel=""
                columns={columns}
                className={s.table}
                data={tableData}
                empty={<EmptyData />}
            ></Table>
            <Dialog
                title={upVisible}
                visible={upVisible}
                confirmText=""
                cancelText=""
                className={s.w540}
                onhide={() => {
                    setUpVisible(false);
                    urlForm.current.resetFields();
                }}
            >
                <div className={cn(i.p24, s.addUser)}>
                    <Form
                        ref={urlForm}
                        {...layout}
                        onValuesChange={(newItem, allValues) => {
                            onValues(newItem, allValues);
                        }}
                    >
                        <Form.Item
                            name="url"
                            label="URL地址"
                            rules={[{ required: true, message: '请输入推送URL地址' }]}
                        >
                            <Input
                                pro
                                className={cn(i.dib, i.w300,s.inpCol)}
                                placeholder={'请输入推送URL地址'}
                                autoComplete={'off'}
                            />
                        </Form.Item>
                        <Form.Item name="authentication" label="是否认证">
                            <Radio.Group className={s.radioBorder}>
                                <Radio value={false} className={s.radio0}>
                                    否
                                </Radio>
                                <Radio value={true} className={s.radio0}>
                                    是
                                </Radio>
                            </Radio.Group>
                        </Form.Item>
                        {/*  */}
                        {showType.auth && (
                            <Form.Item
                                name="auth_type"
                                label="认证类型"
                                rules={[{ required: true, message: '请选择认证类型' }]}
                            >
                                <Select
                                    pro
                                    option={[
                                        { label: 'Api Key', value: 'api_key' },
                                        { label: 'Basic Auth', value: 'basic_auth' },
                                    ]}
                                    className={s.w_30}
                                    placeholder="请选择认证类型"
                                />
                            </Form.Item>
                        )}
                        {showType.auth?.key && (
                            <>
                                <Form.Item
                                    name="auth_key"
                                    label="认证Key"
                                    rules={[{ required: true, message: '请输入认证Key' }]}
                                >
                                    <Input
                                        pro
                                        className={cn(i.dib, i.w300)}
                                        placeholder={'请输入认证Key'}
                                        autoComplete={'off'}
                                    />
                                </Form.Item>
                                <Form.Item
                                    name="auth_value"
                                    label="认证密钥"
                                    rules={[{ required: true, message: '请输入认证密钥' }]}
                                >
                                    <Input
                                        pro
                                        className={cn(i.dib, i.w300)}
                                        placeholder={'请输入认证密钥'}
                                        autoComplete={'off'}
                                    />
                                </Form.Item>
                            </>
                        )}
                        {showType.auth?.user && (
                            <>
                                <Form.Item
                                    name="auth_key"
                                    label="认证用户名"
                                    rules={[{ required: true, message: '请输入认证用户名' }]}
                                >
                                    <Input
                                        pro
                                        className={cn(i.dib, i.w300)}
                                        placeholder={'请输入认证用户名'}
                                        autoComplete={'off'}
                                    />
                                </Form.Item>
                                <Form.Item
                                    name="auth_value"
                                    label="认证密码"
                                    rules={[{ required: true, message: '请输入认证密码' }]}
                                >
                                    <Input
                                        pro
                                        className={cn(i.dib, i.w300)}
                                        placeholder={'请输入认证密码'}
                                        autoComplete={'off'}
                                    />
                                </Form.Item>
                            </>
                        )}
                        {/*  */}
                        <Form.Item
                            name="method"
                            label="请求方式"
                            rules={[{ required: true, message: '请选择请求方式' }]}
                        >
                            <Select
                                pro
                                option={[
                                    { label: 'GET', value: 'GET' },
                                    { label: 'POST', value: 'POST' },
                                ]}
                                className={s.w_30}
                                placeholder="请选择请求方式"
                            />
                        </Form.Item>
                        <Form.Item
                            name="expired_time"
                            label="有效期"
                            rules={[{ required: true, message: '有效期不能为空' }]}
                        >
                            <Datetime
                                disabledDate={disabledate}
                                getPopupContainer={(triggerNode) => triggerNode}
                            />
                        </Form.Item>
                        <Form.Item name="is_active" label="状态">
                            <Select
                                pro
                                option={[
                                    { label: '启用', value: 'true' },
                                    { label: '禁用', value: 'false' },
                                ]}
                                className={s.w_30}
                                placeholder="请选择状态"
                            />
                        </Form.Item>
                        <Form.Item
                            name="desc"
                            label="备注"
                            rules={[{ required: false, validator: validatormap }]}
                        >
                            <Textarea
                                pro
                                className={cn(i.dib, i.w300, s.textarea)}
                                placeholder={'请输入备注'}
                                autoComplete={'off'}
                            />
                        </Form.Item>
                    </Form>
                </div>
                <div className={cn(i.tac, s.dioBtn)}>
                    <Button
                        className={i.vam}
                        onClick={() => {
                            setUpVisible(false);
                            urlForm.current.resetFields();
                        }}
                    >
                        取消
                    </Button>
                    <Button
                        type="primary"
                        className={cn(i.ml24, i.vam)}
                        onClick={() => submitInfo()}
                    >
                        确定
                    </Button>
                </div>
            </Dialog>
        </div>
    );
}
